var express = require('express');
var router = express.Router();
const mongodb= require('../components/mongo');

const multer = require('multer');
const uploader = multer({dest:'uploads/'});



/* GET home page. */
router.get('/',function(req, res, next) {
	res.render('commentSample',{title:'commentSample'});
}).post('/',async function(req,res,next){
	
	var m_aid = req.body.a_id;
	var m_uid = req.body.u_id;
	var m_comment = req.body.comment;
	var m_time_stamp = req.body.time_stamp;
	console.log(req.body);
		   
	if(m_aid == undefined || m_uid == undefined || m_time_stamp == undefined || m_comment == undefined){
		   res.json({
		   		       errno: 0,
		   		       errmsg: "",
		   		       data: {
		   		           res: false
		   		       }
					})	
	}
	const result = await mongodb.find("Article",{a_id:m_aid});
	if(result.length > 0){
			   var a_item = result[0];
			   //update the article
			   a_item.comments.push({
				   u_id : m_uid,
				   comment: m_comment,
				   time_stamp : m_time_stamp
			   })
			   const insert_result = await mongodb.update("Article",{a_id:m_aid},a_item);
			   res.json({
			   		       errno: 0,
			   		       errmsg: "",
			   		       data: {
			   		           res: true
			   		       }
			   			})	
	}else{
		   //article not exist
		   res.json({
		   		       errno: 0,
		   		       errmsg: "",
		   		       data: {
		   		           res: false
		   		       }
		   			})	
	}
})


module.exports = router;



// ### 评论（POST）
// 访问的URL：host/comment  
// 客户端需要指明是哪个帖子（id）被谁（用户id）评论了什么（字符串）：
// ```
// {
//     "a_id" : "13340",
//     "u_id" : "19308024",
//     "comment" : "好耶",
//     "time_stamp" : "2021-11-11 07:58:45"
// }
// ```
// 服务端需要返回成功或失败，并注册一个cid：
// ```
// {
//     "errno": 0,
//     "errmsg": "",
//     "data": {
//         "res": true
//     }
// }
// ```